import axios from 'axios'
import { message } from 'ant-design-vue'

//  * 封装上传文件的post方法
//  * @param url
//  * @param data
//  * @returns {Promise}

// 接口域名地址
let baseURL = process.env.VUE_APP_API_BASE_URL


export function uploads(url, file, oldUserImg) {
    return uploadData(url, file, oldUserImg)
}


function uploadData(url, file, oldUserImg) {
    // 创建 FormData 对象
    let formData = new FormData();
    // 通过 append() 方法来追加数据
    formData.append("files", file)
    formData.append("oldUserImg", oldUserImg)
    return new Promise((resolve, reject) => {
        axios.post(baseURL + url, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'authorization': 'Bearer ' + localStorage.getItem('token'),
            }
        }).then(response => {
            resolve(response)
        }).catch(error => {
            if (error.response) {
                // 对响应错误做点什么
                switch (error.response.status) {
                    case 403:
                        message.error('拒绝访问')
                        break
                    case 500:
                        message.error('很抱歉，登录已过期，请重新登录')
                        localStorage.clear();
                        sessionStorage.clear()
                        setTimeout(() => {
                            window.location.reload()
                        }, 1000)
                        break
                    case 404:
                        message.error('很抱歉，资源未找到!')
                        break
                    case 405:
                        message.error('请求方式错误！')
                        break
                    case 504:
                        message.error('网络超时')
                        break
                    case 401:
                        message.error('未授权，请重新登录')
                        localStorage.clear();
                        sessionStorage.clear()
                        setTimeout(() => {
                            window.location.reload()
                        }, 1000)
                        break
                    default:
                        message.error(data.message)
                        break
                }
            }
            reject(error)
        })
    })
}
